package com.google.code.mochaccino.framework.remote.program;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Program class is meant to allow easy interactions with command-line utilities from
 * the JVM. However, it is machine/platform dependant, so a command working on Machine X
 * may not work on Machine Y.
 */
public class Program {
	private BufferedInputStream  processErrorStream;
	private BufferedInputStream  processOutputStream;
	private BufferedOutputStream processInputStream;
	private File                 workingDir;
	private Process              process;
	private String[]             cmd;
	private String[]             environment;

	protected Logger logger = LoggerFactory.getLogger( getClass() );

	/**
	 * Create Program
	 *
	 * @param cmdLine The Command-Line
	 */
	public Program( String[] cmdLine ) {
		this( cmdLine, null );
	}

	/**
	 * Create Program
	 *
	 * @param cmdLine The Command-Line
	 * @param env     The Environment Variables
	 */
	public Program( String[] cmdLine, String[] env ) {
		this( cmdLine, env, null );
	}

	/**
	 * Create Program
	 *
	 * @param cmdLine The Command-Line
	 * @param env     The Environment Variables
	 * @param dir     The Execution Directory
	 */
	public Program( String[] cmdLine, String[] env, File dir ) {
		cmd = Arrays.copyOf( cmdLine, cmdLine.length );
		if ( env != null ) {
			environment = Arrays.copyOf( env, env.length );
		} else {
			Map<String,String> envMap = System.getenv();
			environment = new String[envMap.size()];
			int i = 0;
			for ( Entry<String,String> e : envMap.entrySet() ) {
				environment[i] = e.getKey() + "=" + e.getValue();
				i++;
			}
		}
		if ( dir != null ) {
			workingDir = dir;
		}
	}

	/** Execute specified program and redirect all output to stdout and stderr */
	public Integer exec() throws IOException {
		return exec( null, System.out, System.err );
	}

	public Integer exec( InputStream in ) throws IOException {
		return exec( in, System.out, System.err );
	}

	/**
	 * Execute Specified Program
	 *
	 * @param stdout The stdout destination
	 * @param stderr The stderr destination
	 */
	public Integer exec( InputStream stdin, OutputStream stdout, OutputStream stderr ) throws IOException {
		Thread processOutputStreamReader = null;
		Thread processErrorStreamReader = null;
		try {
			process = Runtime.getRuntime().exec( cmd, environment, workingDir );
			processInputStream = new BufferedOutputStream( process.getOutputStream() );
			processOutputStream = new BufferedInputStream( process.getInputStream() );
			processErrorStream = new BufferedInputStream( process.getErrorStream() );
			processOutputStreamReader = new Thread( new OutputCollector( processOutputStream, stdout ) );
			processErrorStreamReader = new Thread( new OutputCollector( processErrorStream, stderr ) );
			processOutputStreamReader.start();
			processErrorStreamReader.start();
			if ( stdin != null ) {
				if ( !(stdin instanceof BufferedInputStream) ) {
					stdin = new BufferedInputStream( stdin );
				}
				IOUtils.copy( stdin, processInputStream );
			}
			int value = process.waitFor();
			if ( processOutputStreamReader.isAlive() ) {
				processOutputStreamReader.interrupt();
			}
			if ( processErrorStreamReader.isAlive() ) {
				processErrorStreamReader.interrupt();
			}
			return value;
		} catch ( InterruptedException e ) {
			if ( logger.isTraceEnabled() ) {
				logger.trace( e.getMessage(), e );
			}
			if ( processOutputStreamReader != null && processOutputStreamReader.isAlive() ) {
				processOutputStreamReader.interrupt();
			}

			if ( processErrorStreamReader != null && processErrorStreamReader.isAlive() ) {
				processErrorStreamReader.interrupt();
			}
			return null;
		} finally {
			IOUtils.closeQuietly( stdin );
			IOUtils.closeQuietly( processInputStream );
			IOUtils.closeQuietly( processOutputStream );
			IOUtils.closeQuietly( processErrorStream );
		}
	}

	/** Kill Specified Program */
	public boolean kill() {
		if ( process != null ) {
			process.destroy();
			return true;
		}
		return false;
	}

	private class OutputCollector implements Runnable {
		private InputStream source;

		private OutputStream collector;

		public OutputCollector( InputStream source, OutputStream collector ) {
			this.source = source;
			this.collector = collector;
		}

		@Override
		public void run() {
			try {
				IOUtils.copy( source, collector );
			} catch ( IOException e ) {
				if ( logger.isTraceEnabled() ) {
					logger.trace( e.getMessage(), e );
				}
			}
		}
	}
}